<template>
  <view class="popup-container" v-if="showPopup" @click.self="emit('close')" :class="{ 'show': showPopup }">
    <view class="popup-content" @click.stop>
      <view class="popup-header">
        <text>结算</text>
        <button style="border:none; background-color: #fff;margin-left: 320px;" @click="emit('close')">❌</button>
      </view>
      <view class="payment-options">
        <view class="option" :class="{ active: selectedOption === 'weixin' }" @click="selectOption('weixin')">
          微信
        </view>
        <view class="option" :class="{ active: selectedOption === 'alipay' }" @click="selectOption('alipay')">
          支付宝
        </view>
        <view class="option" :class="{ active: selectedOption === 'cash' }" @click="selectOption('cash')">
          现金
        </view>
        <view class="option" :class="{ active: selectedOption === 'other' }" @click="selectOption('other')">
          其他
        </view>
      </view>
      <view class="summary">
        <view class="item">
          <text>共 {{ totalProducts }} 件商品</text>
          <text>合计：¥{{ totalAmount }}</text>
        </view>
        <view class="divider"></view>
        <view class="item">
          <text>优惠：¥0.00</text>
          <text>应收：¥{{ totalAmount }}</text>
        </view>
      </view>
      <view class="payment-detail" v-if="selectedOption !== 'cash'">
        <text style="font-size: 18px;">{{ paymentMethod }}：</text>
        <view class="amount-box">
          <text style="font-size: 26px;color: #0059df;font-weight: bold;">{{ totalAmount }}</text>
          <text style="line-height: 30px; font-size: 16px;color: #868686;">元</text>
        </view>
      </view>
	  <!-- 现金支付 -->
	   <view class="payment-details" v-if="selectedOption === 'cash'">
	       <view style="display: flex; justify-content: space-between;">
	         <!-- 找零部分 -->
	         <view style="flex: 1; margin-right: 10px; min-width: 45%;">
	           <text style="font-size: 18px;">找零：</text>
	           <view class="amount-box change">
	             <text style="font-size: 26px; color: #0059df; font-weight: bold;">{{ change }}</text>
	             <text style="line-height: 34px; font-size: 16px; color: #868686;">元</text>
	           </view>
	         </view>
	         <!-- 现金支付部分 -->
	         <view style="flex: 1; min-width: 45%;">
	           <text style="font-size: 18px;">现金支付：</text>
	           <view class="amount-box change">
	             <input type="number" v-model="cashPayment" style="font-size: 26px; color: #0059df; font-weight: bold;" />
	             <text style="line-height: 34px; font-size: 16px; color: #868686;">元</text>
	           </view>
	         </view>
	       </view>
	     </view>
	    <!-- 数字键盘 -->
		<view class="numeric-keyboard" v-if="selectedOption === 'cash'">
			<!-- 数字1-9：前三行前三列 -->
			<view 
			  v-for="(num, index) in [1, 2, 3, 4, 5, 6, 7, 8, 9]" 
			  :key="index"
			  class="key"
			  :class="`row${Math.floor(index / 3) + 1}-col${index % 3 + 1}`"
			  @click="handleNumberClick(num)"
			>
			  {{ num }}
			</view>
			<!-- 第四行：0占两列，小数点占一列 -->
			<view class="key double-width" @click="handleNumberClick(0)">0</view>
			<view class="key decimal" @click="handleDecimalClick">.</view>
			<!-- 清除按钮：第四列第一行 -->
			<view class="clear" @click="clearInput">×</view>
			<!-- 确定按钮：第四列第二到第四行（共三行） -->
			<view class="confirm" @click="confirmPayment">确定</view>
		  </view>
      <view class="buttons" v-else>
        <button v-if="selectedOption !== 'other'"  class="show-qr-code" @click="showQRCode">{{showQRButtonText}}</button>
        <button class="confirm" @click="confirmPayment">确定</button>
      </view>
	  <!-- uni-popup 组件用于显示二维码图片 -->
	      <uni-popup ref="popup" type="center">
	        <view class="popup-content">
	          <image :src="selectedQRCode" mode="aspectFit"></image>
	          <button type="default" @tap="closePopup">关闭</button>
	        </view>
	      </uni-popup>
    </view>
  </view>
</template>

<script setup>
import { defineProps, defineEmits, ref, computed,onMounted  } from 'vue';
const popup = ref(null); // 引用 uni-popup 组件
const props = defineProps({
  showPopup: Boolean,
  totalAmount: Number,
  totalProducts:Number,
  orderDetails: {
      type: Array,
      required: true,
      default: () => []
  },
  orderRemark: {
        type: String,
        default: ''
  }
});

const emit = defineEmits(['close']);

const selectedOption = ref('weixin');
const weChatCode = ref(''); // 微信收款码图片路径
const alipayCode = ref(''); // 支付宝收款码图片路径
const selectedQRCode = ref(''); // 用于展示的二维码图片路径
// 加载已保存的收款码图片
onMounted(() => {
  weChatCode.value = uni.getStorageSync('weChatCode') || '';
    console.log("Loaded weChatCode:", weChatCode.value); // 确认加载的数据
    alipayCode.value = uni.getStorageSync('alipayCode') || '';
    console.log("Loaded alipayCode:", alipayCode.value); // 确认加载的数据
});
const selectOption = (option) => {
  selectedOption.value = option;
};

// 根据选定的支付方式动态设置支付方法和按钮文本
const paymentMethod = computed(() => {
  switch (selectedOption.value) {
    case 'weixin':
      return '微信支付';
    case 'alipay':
      return '支付宝支付';
    case 'other':
      return '其他支付';
  }
});

const showQRButtonText = computed(() => {
  switch (selectedOption.value) {
    case 'weixin':
      return '出示微信收款码';
    case 'alipay':
      return '出示支付宝收款码';
    default:
      return '出示付款码';
  }
});
function showQRCode() {
  if (!selectedOption.value) {
    console.log('请选择支付方式');
    return;
  }
  if (selectedOption.value === 'weixin') {
    if (!weChatCode.value) {
      uni.showToast({
        title: '请先在收款码设置中添加微信收款码',
        icon: 'none',
        duration: 2000
      });
	  return;
    }
    selectedQRCode.value = weChatCode.value;
    popup.value.open(); // 打开弹出层
  } else if (selectedOption.value === 'alipay') {
    if (!alipayCode.value) {
      uni.showToast({
        title: '请先在收款码设置中添加支付宝收款码',
        icon: 'none',
        duration: 2000
      });
	  return;
    }
    selectedQRCode.value = alipayCode.value;
    popup.value.open(); // 打开弹出层
  }
}
function closePopup() {
  popup.value.close(); // 关闭弹出层
}
//现金支付
const cashPayment = ref('');
const change = computed(() => {
  const amount = parseFloat(cashPayment.value);
  return amount > props.totalAmount ? (amount - props.totalAmount).toFixed(2) : '0.00';
});
const handleNumberClick = (number) => {
  cashPayment.value += number.toString();
};

const handleDecimalClick = () => {
  if (!cashPayment.value.includes('.')) {
    cashPayment.value += '.';
  }
};
//清空现金输入金额
const clearInput = () => {
  cashPayment.value = '';
};
//收银金额
const confirmPayment = async () => {
	console.log('支付方式:', selectedOption.value); // 确认是否为 'cash'
  // 计算实收金额
  let receivedAmount;
  if (selectedOption.value === 'cash') {
	  console.log("现金进来了")
     // 处理输入值
         const input = cashPayment.value.trim();
        receivedAmount = input ? parseFloat(input) : 0;
        // 检查是否为有效数字
        if (isNaN(receivedAmount)) {
          uni.showToast({
            title: '请输入有效的金额',
            icon: 'error',
			duration: 2000
          });
          return;
        }
        // 验证金额是否足够
        if (receivedAmount < props.totalAmount) {
			 console.log('触发现金不足提示'); // 确认是否执行到这里
          uni.showToast({
            title: '现金不足',
            icon: 'error',
			duration: 2000,
			top:0,
			mask: true // 显示遮罩层，但可能需要调整样式
          });
          return;
        }
		console.log('输入金额:', cashPayment.value);
		console.log('解析后的金额:', receivedAmount);
		console.log('总金额:', props.totalAmount);
      } else {
        receivedAmount = props.totalAmount;
      }
	   //发送订单请求到后端
	     try {
	       const response = await uni.request({
	         url: 'http://localhost:15000/SALE-SERVICE/sale/create',
	         method: 'POST',
	         data: {
	           amountDue: props.totalAmount,
			   remarks:props.orderRemark,
			   actualReceivedAmount:props.totalAmount,
	           // 传递完整的订单明细
	           orderDetails: props.orderDetails.map(detail => ({
	                productId: detail.productId,
	                quantity: detail.qutity,
	                unitPrice: detail.retailPrice
	            }))
	         }
	       });
	       // 成功后才触发后续操作
	       if (response.data != null) {
	         emit('payment-success', {
	           method: selectedOption.value,
	           amount: receivedAmount,
	           change: change.value
	         });
	         emit('close');
	         uni.showToast({
	           title: `完成收银！实收金额：¥${receivedAmount}`,
	           icon: 'success',
	           duration: 2000
	         });
	         cashPayment.value = '';
	       } else {
	         uni.showToast({
	           title: '订单创建失败，请重试',
	           icon: 'none'
	         });
	       }
	     } catch (error) {
	       uni.showToast({
	         title: '网络请求失败',
	         icon: 'none'
	       });
	     }
  // // 触发收银完成事件
  // emit('payment-success', {
  //   method: selectedOption.value,
  //   amount: receivedAmount,
  //   change: change.value
  // });
  // // 关闭弹窗
  // emit('close');
  // // 显示成功提示
  // uni.showToast({
  //   title: `完成收银！实收金额：¥${receivedAmount}`,
  //   icon: 'success',
  //   duration: 2000
  // });
  // // 清空现金输入框
  // cashPayment.value = '';
};
</script>

<style scoped>
	.uni-toast {
	  z-index: 1000;
	}
.popup-container {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  max-height: 80vh;
  background-color: white;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.2);
  padding: 10px;
  box-sizing: border-box;
  z-index: 999;
  transform: translateY(100%);
  transition: all 0.3s ease;
}

.show {
  transform: translateY(0);
}

.popup-content {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.payment-options {
  display: flex;
  border: 1px solid #007bff;
  border-radius: 4px;
  overflow: hidden;
}

.option {
  flex: 1;
  padding: 10px;
  text-align: center;
  cursor: pointer;
  border-right: 1px solid #007bff;
}

.option:last-child {
  border-right: none;
}

.option.active {
  background-color: #007bff;
  color: white;
}

.summary {
  margin-top: 20px;
  border-bottom: 1px solid #ccc;
  padding-bottom: 10px;
}

.item {
  display: flex;
  justify-content: space-between;
}

.divider {
  height: 1px;
  background-color: #ccc;
  margin: 10px 0;
}

.payment-detail {
  margin-top: 10px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.amount-box {
  height: 34px;
  background-color: #f6f6f6;
  border-radius: 8px;
  padding: 10px;
  display: flex;
  justify-content: space-between;
  gap: 10px;
  flex: 1;
}

.buttons {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  cursor: pointer;
}

.show-qr-code {
  background-color: #e6e6e6;
  border-radius: 8px;
  padding: 10px;
  flex: 1;
}

.confirm {
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 8px;
  padding: 10px;
  flex: 1;
}

.payment-details{
	display: flex;
	flex-direction: row;
	justify-content: space-between;
	align-items: center;
}
.change {
  margin-top: 10px;
}

.numeric-keyboard {
  display: grid;
  grid-template-columns: repeat(4, 1fr); /* 四列 */
  grid-template-rows: repeat(4, 1fr);    /* 四行 */
  gap: 10px;
  padding: 10px;
  background-color:#f5f5f5 ;
}

.key {
  background-color: #ffffff;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: #333;
  cursor: pointer;
  height: 100%; /* 填满行高 */
}

/* 第四行的0占两列 */
.key.double-width {
  grid-column: 1 / 3; /* 从第一列到第三列（占据两列） */
  grid-row: 4;        /* 第四行 */
}
/* 小数点占第四行第三列 */
.key.decimal {
  grid-column: 3;
  grid-row: 4;
}
/* 清除按钮：第四列第一行 */
.clear {
  background-color: white;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  grid-column: 4;
  grid-row: 1; /* 第一行 */
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: #333;
  cursor: pointer;
}
/* 确定按钮：第四列第二到第四行（共三行） */
.confirm {
  background-color: #0059df;
  color: white;
  border: none;
  border-radius: 8px;
  grid-column: 4;
  grid-row: 2 / 5; /* 从第二行到第四行（包含第二行，不包含第五行） */
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  cursor: pointer;
}

/* 数字1-9的具体位置 */
.key.row1-col1 { grid-row: 1; grid-column: 1; }
.key.row1-col2 { grid-row: 1; grid-column: 2; }
.key.row1-col3 { grid-row: 1; grid-column: 3; }
.key.row2-col1 { grid-row: 2; grid-column: 1; }
.key.row2-col2 { grid-row: 2; grid-column: 2; }
.key.row2-col3 { grid-row: 2; grid-column: 3; }
.key.row3-col1 { grid-row: 3; grid-column: 1; }
.key.row3-col2 { grid-row: 3; grid-column: 2; }
.key.row3-col3 { grid-row: 3; grid-column: 3; }
</style>